package com.tianqu.tms.core.taglib;

import java.io.Serializable;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * @author liugang
 *
 */
public class MenuManager implements Serializable {
	private static final long serialVersionUID = 1; 
	private MenuBean menuVo = null; 
	/**
	 * 
	 * @param navigatVO
	 */
	public MenuManager(MenuBean navigatVO) {
		this.menuVo = navigatVO;
	}
	
	/**
	 * 
	 * @param funcId
	 * @return
	 */
	public MenuBean getActivTree(String funcId){
		int startLev = getLevel(menuVo.getFunctionId());
		int endLev = getLevel(funcId);
		MenuBean tmpVO = new MenuBean();
		tmpVO = null;
		MenuBean targetVO = null;
		for (int i = endLev; i>=startLev; i-- ) {
			targetVO = new MenuBean();
			String id = getBossId(i,funcId);
			targetVO.copy(menuVo.getMenuVO(id));
			List<MenuBean> list = new ArrayList();
			if (tmpVO != null){
				list.add(tmpVO);
			}
			targetVO.setChildrenList(list);
			tmpVO = targetVO;
		}
		return targetVO;
	}
	/**
	 * 
	 * @param bossLevel
	 * @param targetFuncId
	 * @return
	 */
	public String getBossId(int bossLevel, String targetFuncId){
		return getBossId(menuVo,bossLevel,targetFuncId,null);
	}
	/**
	 * 
	 * @param vo
	 * @param bossLevel
	 * @param targetFuncId
	 * @param bossId
	 * @return
	 */
	private  String getBossId(MenuBean vo, int bossLevel, String targetFuncId, String bossId){
		String tempId = vo.getFunctionId();
		int level = getLevel(tempId);
		if (level == bossLevel){
			bossId = tempId;
		}
		if (compstr(targetFuncId, tempId)){
			return bossId;
		}
		
		String s = null;
		if (level < getLevel(targetFuncId)) {
			for ( Iterator iterator = vo.getChildrenList().iterator();iterator.hasNext(); ) {
				s= getBossId((MenuBean)iterator.next(), bossLevel, targetFuncId, bossId);
				if ( s!= null ) {
					break;
				}
			}
		}
		return s;
	}
	/**
	 * 
	 * @param level
	 * @param targetFuncId
	 * @param currentFuncId
	 * @return
	 */
	public boolean equalsBossId(int level, String targetFuncId, String currentFuncId){
		if (getLevel(currentFuncId)<level){
			return false;
		}
		String bossId = getBossId(level,targetFuncId);
		String selectedBossId = getBossId(level,currentFuncId);

		return compstr(selectedBossId, bossId);
	}
	/**
	 * 
	 * @param functionId
	 * @return
	 */
	public int getLevel(String functionId){
		return menuVo.getChildLevelCount(functionId)-1;
	}
	/**
	 * 
	 * @param s1
	 * @param s2
	 * @return
	 */
	protected boolean compstr(String s1, String s2) {
		Collator myCollator = Collator.getInstance();
		boolean b = (myCollator.compare(s1, s2) == 0);
		return b;
	}
}
